<template>
  <div class="container-fluid">
    <!-- 顶部导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="row align-items-center">
        <div class="col-md-auto">
          <h1>停车场管理系统</h1>
        </div>
        <div class="col-md"></div>
        <div class="col-md-auto text-right">
          <span>{{ username }}</span>
          <router-link to="/" class="btn btn-light ml-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light ml-2">退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="col-md-12 mt-4">
      <div class="card">
        <div class="card-header bg-secondary text-white">
          <h2 class="text-center">报表管理</h2>
        </div>
        <div class="card-body">
          <div class="mb-4">
            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <label for="reportType">报表类型</label>
                  <select class="form-control" id="reportType" v-model="reportType">
                    <option value="daily">日报</option>
                    <option value="weekly">周报</option>
                    <option value="monthly">月报</option>
                    <option value="quarterly">季报</option>
                    <option value="yearly">年报</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label for="startDate">开始日期</label>
                  <input type="date" class="form-control" id="startDate" v-model="startDate">
                </div>
              </div>
            </div>
          </div>
          
          <!-- 查询列表 -->
          <div class="mt-4">
            <h3>{{ reportType === 'daily' ? '日报' : reportType === 'weekly' ? '周报' : reportType === 'monthly' ? '月报' : reportType === 'quarterly' ? '季报' : '年报' }}</h3>
            
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>日期</th>
                  <th>总车流量</th>
                  <th>总收入</th>
                  <th>单车平均收入</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in reportData" :key="item.date">
                    <td>{{ item.date }}</td>
                    <td>{{ item.totalTraffic }}</td>
                    <td>{{ item.totalRevenue }}</td>
                    <td>{{ item.averageRevenuePerCar }}</td>
                  </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ReportView',
  data() {
    return {
      username: '',
      reportType: 'daily',
      startDate: '',
      reportData: []
    }
  },
  watch: {
    // 当报表类型或开始日期改变时，自动获取数据
    reportType() {
      this.fetchReportData()
    },
    startDate() {
      if (this.startDate) {
        this.fetchReportData()
      }
    }
  },
  mounted() {
    this.username = localStorage.getItem('username') || '管理员'
    // 设置默认日期为今天
    const today = new Date()
    this.startDate = this.formatDate(today)
    // 页面加载后自动获取数据
    this.fetchReportData()
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 获取报表类型对应的状态码
    getReportStatus() {
      const statusMap = {
        'daily': 0,
        'weekly': 1,
        'monthly': 2,
        'quarterly': 3,
        'yearly': 4
      }
      return statusMap[this.reportType] || 0
    },
    
    // 从后端获取报表数据
    fetchReportData() {
      if (!this.startDate) {
        return
      }
      
      const status = this.getReportStatus()
      
      axios.get('/api/report/generate', {
        params: {
          status: status,
          date: this.startDate
        }
      })
      .then(response => {
        const result = response.data
        
        // 检查是否有错误
        if (result.status === -1) {
          alert(result.dates) // 显示错误信息
          this.reportData = []
          return
        }
        
        // 格式化后端数据为前端表格所需的格式
        this.reportData = [{ 
          date: result.dates, 
          totalTraffic: result.carNumber, 
          totalRevenue: result.money.toFixed(2), 
          averageRevenuePerCar: result.price.toFixed(2) 
        }]
      })
      .catch(error => {
        console.error('获取报表数据失败:', error)
        alert('获取报表数据失败，请稍后重试')
        this.reportData = []
      })
    }
  }
}
</script>

<style >
/* 这里可以添加组件特定的样式 */
</style>